package com.atguigu.tingshu.live.config;

import com.atguigu.tingshu.common.constant.RedisConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.lang.Nullable;

/**
 * title:
 * author: zgl
 * date: 2024/3/5
 * description：
 */
@Configuration
public class RedisListenerConfig {
    @Autowired
    private RedisTemplate redisTemplate;

    @Bean
    public RedisMessageListenerContainer listenerContainer(RedisConnectionFactory redisConnectionFactory) {
        RedisMessageListenerContainer listenerContainer = new RedisMessageListenerContainer();
        //设置工厂
        listenerContainer.setConnectionFactory(redisConnectionFactory);
        //
        listenerContainer.addMessageListener((Message message, @Nullable byte[] pattern) -> {
            String msg = redisTemplate.getValueSerializer().deserialize(message.getBody()).toString();
            LiveRoomUtil.sendMsg(msg);
        }, new ChannelTopic(RedisConstant.CHANNEL_KEY_PREFIX));
        return listenerContainer;
    }
}
